package com.cqhz.quwan.util;

import android.os.Build;
import android.text.TextUtils;

import com.blankj.utilcode.util.EncryptUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.Request;

/**
 * Created by GuoJing on 2018/11/06.
 * OkHttp3 拦截器工具类
 */
public class InterceptorUtil
{
    private static final String TAG                      = "InterceptorUtil";
    private static final String HEADER_NAME_SOURCE       = "source";
    private static final String HEADER_NAME_LOCATION     = "location";
    private static final String HEADER_NAME_APPKEY       = "appKey";
    private static final String HEADER_NAME_CHANEL       = "channel";
    private static final String HEADER_NAME_PHONE_MOBILE = "phoneModel";
    private static final String HEADER_NAME_EQUIPMENT    = "equipmentId";
    private static final String HEADER_KEY_TIMESTAMP     = "timestamp";//客户端时间戳
    private static final String HEADER_KEY_SIGNATURE     = "signature";//签名信息
    private static final String PUBLIC_KEY               = "040CD66A84025B94CEAC3EC1B49C92D0";

    /**
     * 网络日志信息拦截器
     *
     * @return
     */
    public static LoggerInterceptor LogInterceptor()
    {
        return new LoggerInterceptor(TAG, true);
    }

    /**
     * 头信息处理拦截器
     *
     * @return
     */
    public static Interceptor HeaderInterceptor()
    {
        return chain -> {
            Request request = chain.request();
            Map<String, String> headMap = new HashMap<>();

            String appKey = "ZQXQ-LOTTERY";
            String appSource = "3";
            String appChannel = "EXH5";
            String timeMillis = String.valueOf(System.currentTimeMillis());

            String brand = Build.BRAND;
            String model = Build.MODEL;

            String phoneIMEI = APPUtil.getPhoneIMEI();

            headMap.put(HEADER_NAME_APPKEY, appKey);
            headMap.put(HEADER_NAME_CHANEL, appChannel);
            headMap.put(HEADER_NAME_SOURCE, appSource);
            headMap.put(HEADER_NAME_PHONE_MOBILE, brand + model);
            headMap.put(HEADER_NAME_EQUIPMENT, phoneIMEI);
            headMap.put(HEADER_KEY_TIMESTAMP, timeMillis);
            headMap.put(HEADER_NAME_LOCATION, "1");

            String md5ToStr = EncryptUtils.encryptMD5ToString(getParamStr(headMap));
            String secondMd5Str = EncryptUtils.encryptMD5ToString(PUBLIC_KEY + md5ToStr);
            headMap.put(HEADER_KEY_SIGNATURE, secondMd5Str);
            FormBody formBody = createNewFormBody(headMap);

            Request.Builder newBuilder = request.newBuilder();
            Request newRequest = newBuilder.method(request.method(), formBody).build();
            return chain.proceed(newRequest);
        };
    }

    private static FormBody createNewFormBody(Map<String, String> params)
    {
        FormBody.Builder builder = new FormBody.Builder();
        for (String key : params.keySet())
        {
            String value = params.get(key);
            if (!TextUtils.isEmpty(key))
            {
                builder.addEncoded(key, value);
            }
        }
        return builder.build();
    }

    private static String getParamStr(Map<String, String> headMap)
    {
        StringBuilder sb = new StringBuilder();
        Iterator<String> iterator = headMap.keySet().iterator();

        List<String> keyList = new ArrayList<>();

        while (iterator.hasNext())
        {
            keyList.add(iterator.next());
        }
        Collections.sort(keyList);

        for (String key : keyList)
        {
            if (!key.startsWith("text") && !key.startsWith("file") && !key.startsWith("unSign"))
            {
                try
                {
                    String value = headMap.get(key);
                    if (!TextUtils.isEmpty(value))
                    {
                        continue;
                    }
                    sb.append(key).append("=").append(value).append("&");
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }

        }
        if (sb.length() > 1)

        {
            sb.deleteCharAt(sb.length() - 1);
        }

        return sb.toString();
    }
}
